<template>
  <div class="app-container">
    <div class="filter-container">
      <el-row :gutter="10">
        <el-col :span="6">
          <el-input
            v-model="searchEntity.entity.roleName"
            placeholder="请输入角色名称"
            @keyup.enter.native="search"
          />
        </el-col>
        <el-col :span="18">
          <el-button type="primary" @click="search">查询</el-button>
        </el-col>
      </el-row>
    </div>
    <div class="filter-container">
      <el-button
        v-permission="['ROLE_SUPERADMIN', 'system:role:addnew']"
        type="primary"
        @click="toAdd"
      ><i class="el-icon-plus" />添加角色</el-button>
    </div>
    <el-table :data="roleTableData" stripe border style="width: 100%">
      <el-table-column type="index" label="序号" width="50" align="center" />
      <el-table-column prop="roleName" label="角色名称" width="180" />
      <el-table-column prop="roleCode" label="角色编码" />
      <el-table-column
        prop="createTime"
        label="创建时间"
        :formatter="rendererDateTime"
      />
      <el-table-column label="操作" width="300">
        <template slot-scope="scope">
          <el-button
            type="success"
            @click="grantPermission(scope.row)"
          >分配权限</el-button>
          <el-button
            type="warning"
            @click="modifyRole(scope.row.id)"
          >修改</el-button>
          <el-button
            v-if="scope.row.userType != 1"
            type="danger"
            @click="removeRole(scope.row.id)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      layout="prev, pager, next"
      :total="searchEntity.totalRecords"
      @current-change="jumpPagination"
    />
    <el-dialog
      :title="dialogType === 'Add' ? '新增角色' : '修改角色'"
      :visible.sync="dialogFormVisible"
      width="600px"
    >
      <el-form
        ref="roleForm"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="角色名称" prop="roleName">
              <el-input v-model="formData.roleName" type="text" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色编码" prop="roleCode">
              <el-input v-model="formData.roleCode" type="text" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="描述" prop="description">
              <el-input
                v-model="formData.description"
                type="textarea"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRole">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 分配权限 -->
    <el-dialog
      title="分配权限"
      :visible.sync="grantDialogVisible"
      width="500px"
    >
      <div>
        <el-tree
          ref="tree"
          :data="treeData"
          show-checkbox
          node-key="id"
          :default-expanded-keys="selectedPermission"
          :default-checked-keys="selectedPermission"
          :props="treeProps"
        />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="grantDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="grant"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  roleList,
  addRole,
  removeRole,
  getRoleById,
  updateRole,
  getPermissionByRoleId,
  grantPerssion
} from '@/api/role'
import { formatTime, deepClone } from '@/utils'
import permission from '@/directive/permission/index.js'
import { getRepeatToken } from '@/api/global'
export default {
  name: 'RoleIndex',
  directives: {
    permission
  },
  data() {
    return {
      searchEntity: {
        pageNum: 1,
        pageSize: 10,
        entity: {
          roleName: ''
        },
        totalRecords: 0
      },
      roleTableData: [],
      formData: {
        createBy: '',
        createTime: null,
        description: '',
        id: '',
        roleCode: '',
        roleName: '',
        updateBy: '',
        updateTime: null
      },
      temp: {},
      dialogType: 'Add',
      dialogFormVisible: false,
      rules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        roleCode: [
          { required: true, message: '请输入角色编码', trigger: 'blur' }
        ]
      },
      repeatToken: '',
      grantDialogVisible: false,
      treeData: [],
      treeProps: {
        children: 'children',
        label: 'menuName'
      },
      currentRole: {},
      selectedPermission: []
    }
  },
  created() {
    this.temp = deepClone(this.formData)
    this.initData()
  },
  methods: {
    initData() {
      getRepeatToken().then((res) => {
        this.repeatToken = res.data.token
      })
      roleList(this.searchEntity).then((res) => {
        this.searchEntity.totalRecords = res.data.pageInfo.total
        this.roleTableData = res.data.pageInfo.list
      })
    },
    search() {
      this.searchEntity.pageNum = 1
      this.initData()
    },
    jumpPagination(num) {
      this.searchEntity.pageNum = num
      this.initData()
    },
    rendererDateTime(row, column, cellValue, index) {
      return formatTime(cellValue)
    },
    toAdd() {
      this.formData = deepClone(this.temp)
      this.dialogType = 'Add'
      this.dialogFormVisible = true
    },
    saveRole() {
      this.$refs['roleForm'].validate((valid) => {
        if (valid) {
          if (this.dialogType == 'Add') {
            addRole(this.formData, { token: this.repeatToken })
              .then((res) => {
                if (res.meta.code == 200) {
                  this.$message.success('操作成功!')
                  this.dialogFormVisible = false
                }
                this.initData()
              })
              .catch((err) => {
                this.initData()
              })
          } else {
            updateRole(this.formData, { token: this.repeatToken })
              .then((res) => {
                if (res.meta.code == 200) {
                  this.$message.success('操作成功!')
                  this.dialogFormVisible = false
                }
                this.initData()
              })
              .catch((err) => {
                this.initData()
              })
          }
        } else {
          return false
        }
      })
    },
    removeRole(id) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          removeRole(id, { token: this.repeatToken }).then((res) => {
            if (res.meta.code == 200) {
              this.initData()
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    modifyRole(id) {
      getRoleById(id).then((res) => {
        this.formData = res.data.data
        this.dialogType = 'Mol'
        this.dialogFormVisible = true
      })
    },
    grantPermission(row) {
      getPermissionByRoleId(row.id).then((res) => {
        this.currentRole = row
        this.treeData = res.data.list
        this.grantDialogVisible = true
        this.selectedPermission = res.data.selected
      })
    },
    grant() {
      const selectPermission = this.$refs.tree.getCheckedNodes()
      if (!selectPermission) return
      const arr = new Array()
      selectPermission.forEach(v => {
        arr.push({ roleId: this.currentRole.id, permId: v.id, type: v.type })
      })
      grantPerssion(arr, { token: this.repeatToken }).then(res => {
        if (res.meta.code == 200) {
          this.$message.success('操作成功!')
          this.grantDialogVisible = false
          this.initData()
        }
      })
    }
  }
}
</script>
